package org.faesa.masterSlave.master;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.AccessException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Master {
	public final static String ARQUIVO_CIFRADO = "cifrado.txt";
	public final static String ARQUIVO_DICIONARIO = "dicionario.txt";
	public final static String FIND_KEY = "FAESA";
	
	public void run() {
		CypherReader reader = null;
		try {
			System.out.print("Trying to read files...");
			
			reader = new CypherReader(Master.ARQUIVO_DICIONARIO, Master.ARQUIVO_CIFRADO);
			SlaveDecodeTextTask.setEncodedText(reader.getText());
			SlaveDecodeTextTask.setFindKey(Master.FIND_KEY);
			
			System.out.println("done");
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			return; // bica! \o/
		}
		catch (IOException e) {
			System.out.println("impossible to read");
		}
		
		Registry registry = null;
		try {
			System.out.print("Listening on port " + Registry.REGISTRY_PORT + "...");
			registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
			
			System.out.println("done");
		} catch (RemoteException e) {
			System.out.println("error");
		}
		
		try {
			System.out.print("Registering...");
			registry.bind("registration", new SlaveRegistrationImpl());
			System.out.println("done");
		} catch (AccessException e) {
			System.out.println("access error...aborting");
			return;
		} catch (RemoteException e) {
			System.out.println("error...aborting");
			return;
		} catch (AlreadyBoundException e) {
			System.out.println("already bound");
		}
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e1) {
		}
		
		String key;
		try {
			while ((key = reader.nextKey()) != null) {
				SlaveDecodeTextTask.newKey(key); 
			}
		}
		catch (InterruptedException e) {
		}
		catch (IOException e) {
		}
		
		System.out.print("Shutdown signal...");		
		System.out.println("done");
	}

	
	public static void main(String[] args) {
		Master master = new Master();
		master.run();
	}
}
